<template>
  <div>
    <div style="margin-bottom: 10px;position: relative;">
      <a-form-model :model="model" ref="form">
        <a-row>
          <!--          <a-col :span="6">-->
          <!--            <a-form-model-item-->
          <!--              label='领料单位'-->
          <!--              :label-col='{span:6}'-->
          <!--              :wrapper-col="{span:16}"-->
          <!--              style='margin-bottom: 0'-->
          <!--              :rules='{trigger: "blur",required:true,message: "请输入领料单位"}'-->
          <!--              prop='pickingDepartment'-->
          <!--            >-->
          <!--              <j-search-select-tag v-model='model.pickingDepartment' :dict-options="departOptions"-->
          <!--                                   ></j-search-select-tag>-->
          <!--            </a-form-model-item>-->
          <!--          </a-col>-->
          <a-col :span="6">
            <a-form-model-item
              label="单据日期"
              :label-col="{ span: 6 }"
              style="margin-bottom: 0"
              :rules="{ trigger: 'blur', required: true, message: '请输入单据日期' }"
              prop="documentDate"
            >
              <j-date v-model="model.documentDate"></j-date>
            </a-form-model-item>
          </a-col>
        </a-row>
      </a-form-model>
      <div style="position: absolute;right: 0;top: 0">
        <a-space>
          <a-button type="primary" v-if="!editable" @click="editAll()">编辑</a-button>
          <a-button type="primary" v-else @click="saveAll()">保存</a-button>
          <a-button v-if="selectedRowKeys.length > 0" type="danger" @click="batchDelVirtual('materialCode')">
            批量删除
            <a-icon type="delete" />
          </a-button>
        </a-space>
      </div>
    </div>

    <a-table
      ref="table"
      size="small"
      bordered
      :columns="columns"
      :dataSource="dataSource"
      :loading="loading"
      :rowKey="record => record.materialCode"
      :pagination="false"
      :rowSelection="{ selectedRowKeys: selectedRowKeys, onChange: onSelectChange }"
      @change="handleTableChange"
    >
      <template slot-scope="text, record" slot="planPickingNumber">
        <a-input-number
          v-model:value="record.planPickingNumber"
          v-if="editable"
          @change="handlePikingNumberChange(arguments, record)"
        ></a-input-number>
        <span :style="{ color: record.isPickingNumberChange ? 'red' : '' }" v-else>{{ text }}</span>
      </template>

      <template slot="warehouse" slot-scope="text, record">
        <j-dict-select-tag
          v-model:value="record.warehouse"
          v-if="editable"
          dict-code="hf_warehouse,warehouse_name,id"
          @change="changInputWarehouse($event, record)"
          style="width: 100px;"
        ></j-dict-select-tag>
        <span v-else>{{ record.warehouse_dictText }}</span>
      </template>

      <template slot="planProduceNumber" slot-scope="text, record">
        <a-tooltip arrow-point-at-center>
          <template slot="title">
            <div
              :style="index === record['planProduceNumberNote'].split(';').length - 1 ? {} : { marginBottom: '6px' }"
              v-for="(item, index) in record['planProduceNumberNote'].split(';')"
            >
              <a-space>
                <span>{{ item.split(',')[0] }}</span>
                <a-tag :color="getRandomColorLimited(index)">{{ item.split(',')[1] }}</a-tag>
              </a-space>
            </div>
            <!--            <div> {{ record['planProduceNumberNote'] }}</div>-->
          </template>
          <span>{{ text }}</span>
        </a-tooltip>
      </template>
    </a-table>
  </div>
</template>

<script>
import { getAction, postAction } from '@api/manage'
import { JeecgListMixin } from '@/mixins/JeecgListMixin'
import { ajaxGetDictItems, getDictItemsFromCache } from '@api/api'
import { getRandomColorLimited } from '@/utils/util'

export default {
  name: 'GenPickingEntry',
  mixins: [JeecgListMixin],
  // inject:[' productionLines'],
  // watch:{
  //   productionLines(val){
  //     console.log("productionLines",val)
  //   }
  // },
  data() {
    return {
      model: {
        documentDate: this.$dayjs(new Date()).format('YYYY-MM-DD')
      },
      disableMixinCreated: true,
      /* 排序参数 */
      isorter: {
        column: 'materialCode',
        order: 'asc'
      },
      /* table加载状态 */
      loading: false,
      editable: false,
      columns: [
        {
          title: '物料代码',
          align: 'center',
          dataIndex: 'materialCode',
          scopedSlots: { customRender: 'materialCode' }
        },
        {
          title: '物料名称',
          align: 'center',
          dataIndex: 'materialName'
        },
        {
          title: '规格型号',
          align: 'center',
          dataIndex: 'sap'
        },
        {
          title: '单位',
          align: 'center',
          dataIndex: 'unit_dictText'
        },
        {
          title: '物料类型',
          align: 'center',
          dataIndex: 'materialType_dictText'
        },
        {
          title: '发料仓库',
          align: 'center',
          dataIndex: 'warehouse',
          scopedSlots: { customRender: 'warehouse' }
        },
        {
          title: '计划生产数',
          align: 'center',
          dataIndex: 'planProduceNumber',
          scopedSlots: { customRender: 'planProduceNumber' }
        },
        {
          title: '计划领料数',
          align: 'center',
          dataIndex: 'planPickingNumber',
          scopedSlots: { customRender: 'planPickingNumber' }
        }
      ],
      url: {
        generatePicking: '/production/hfProductionPicking/generatePicking',
        depart: '/sys/sysDepart/queryByParentId'
      },
      departOptions: []
    }
  },
  created() {
    this.initDictOptions()
  },
  methods: {
    getRandomColorLimited,
    initDictOptions() {
      if (getDictItemsFromCache(`sys_depart,depart_name,id,制造课`)) {
        this.departOptions = getDictItemsFromCache(`sys_depart,depart_name,id,制造课`)
        return
      }
      getAction(this.url.depart, { parentDepartName: '制造课' }).then(res => {
        if (res.success) {
          this.departOptions = res.result.map(item => {
            return {
              value: item.id,
              text: item.departName
            }
          })
        }
      })
    },
    close() {
      this.$emit('close')
      this.visible = false
    },
    handleOk(productMissionId, productMissionSerial, orderIds, workShift) {
      this.confirmLoading = true
      let params = {
        documentDate: this.model.documentDate,
        pickingDepartment: this.model.pickingDepartment,
        productMissionId: productMissionId,
        productMissionSerial: productMissionSerial,
        productOrderIds: orderIds.join(','),
        workShift: workShift
      }
      postAction(this.url.generatePicking, this.dataSource, { params: params })
        .then(res => {
          if (res.success) {
            this.$message.success(res.message)
            this.close()
          } else {
            this.$message.warning(res.message)
          }
        })
        .finally(() => {
          this.confirmLoading = false
          this.$emit('ok', true)
        })
    },
    handleCancel() {
      this.close()
    },
    onSelectChange(selectedRowKeys, selectionRows) {
      this.selectedRowKeys = selectedRowKeys
      this.selectionRows = selectionRows
    },
    loadData1(data) {
      this.dataSource = data
    },
    changInputWarehouse(warehouse, record) {
      const newData = [...this.dataSource]
      const target = this.dataSource.find(item => item.materialCode === record.materialCode)
      let dictOptions
      ajaxGetDictItems('hf_warehouse,warehouse_name,id', null).then(res => {
        if (res.success) {
          dictOptions = res.result
          target.warehouse_dictText = dictOptions.find(item => item.value === record.warehouse).text
          target.warehouse = warehouse
          this.dataSource = newData
        }
      })
    },
    editAll() {
      this.editable = true
    },
    saveAll() {
      this.editable = false
      // const newData = [...this.dataSource]
      // this.dataSource = newData
    },
    handlePikingNumberChange([value], record) {
      record.isPickingNumberChange = true
    }
  }
}
</script>

<style scoped></style>
